package com.wgj.android.accesslibility.job;
import android.accessibilityservice.AccessibilityService;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiaai.xui.adapter.XRecyclerViewAdapter;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.accesslibility.AccessibilityHelper;
import com.wgj.android.accesslibility.IStatusBarNotification;
import com.wgj.android.accesslibility.config.BatchGroupConfig;
import com.wgj.android.accesslibility.config.WXConfginUtil;
import com.wgj.android.accesslibility.config.WXIDManage;
import com.wgj.android.accesslibility.config.WXPageUIManage;
import com.wgj.android.accesslibility.service.WGJAccessServier;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.ui.activity.MainActivity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/12/20.
 */

public class AddFriendsByGroupJob implements AccessbilityJob {
    private static  final   int SEND_MSG=1;
    private static  final  int CHECK_GROUP=2;
    private static  final  int CHECK_FRIEND=3;

    private  boolean isToSendMsg=false;
    private BatchGroupConfig config;
    private WGJAccessServier servier;
    //当前检测的群组
    private  String checkGroupName;
    //当前页面的检测索引
    private int indexOf=0;
    //当前已检测的人数
    private int addNumber=0;
    //当前是否是已检测
    private boolean isCheck=false;
    //当前群总人数
    private int totalNum=0;
    private  boolean isStart=false;
    private int weixinVersion;

    private  List<String>  filterGroups=new ArrayList<>();
    private  ArrayList<String> adds=new ArrayList<>();
    private HashSet<String> addFriends=new HashSet<>();


    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private boolean viewAdded = false;// 透明窗体是否已经显示
    private View startWarp;
    private View mainWarp;
    private Chronometer time3;
    private View view;// 透明窗体
    private View a1;
    private TextView timepicker;
    private TextView tvTotalNum;
    private XRecyclerViewAdapter adapter;
    private  TextView msgText;//进程消息
    private  TextView tvCleanNumber;
    private  TextView tvStatus;//好友状态
    private PowerManager.WakeLock wakeLock;
    private  String nickName;
    private  String className;
    private  boolean isClickGroupItem=false;//是否已经点击了 群
    private  boolean isCheckFriends=false;
    private Timer mTimer;

    @Override
    public String getTargetPackageName() {
        return WECHAT_PACKAGENAME;
    }

    @Override
    public void onCreateJob(AccessibilityService service) {
        this.servier= (WGJAccessServier) service;
        adds=new ArrayList<>();
        config= WXConfginUtil.getBatchGroupConfig(service.getApplication());
        filterGroups=config.getGroupIndex();
        addFriends=WeiXinCacheUtil.getAddFirendsByGroup(service.getApplication());
        /**常亮*/
        PowerManager pm = (PowerManager) service.getApplication().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
        wakeLock.acquire();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onReceiveJob(AccessibilityEvent event) {
        className= event.getClassName().toString();

        if(!className.equals("com.tencent.mm.ui.LauncherUI") && !isStart){
            AccessibilityHelper.performBack(servier);
            return;
        }
        if(className.equals("com.tencent.mm.ui.base.i")){
            try {
                AccessibilityNodeInfo nodeInfo=AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"确定");
                if(nodeInfo!=null){
                    if(mTimer!=null){
                        mTimer.cancel();
                        mTimer.purge();
                        mTimer=null;
                    }
                    AccessibilityHelper.performClick(nodeInfo);
                }
            }catch (Exception e){

            }
            return;
        }
        if(WXPageUIManage.isMainUI(event.getClassName().toString())){
            try {
                if(!viewAdded){
                    if(AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"通讯录")==null){
                        AccessibilityHelper.performBack(servier);
                        return;
                    }
                    createWindow();
                }else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if(mTimer!=null){
                                mTimer.cancel();
                                mTimer.purge();
                                mTimer=null;
                            }
                            AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"通讯录"));
                            try {
                                Thread.sleep(300);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"群聊"));
                            isStart=true;
                        }
                    }).start();
                }
            }catch (Exception e){

            }
            return;
        }
       if(className.equals("com.tencent.mm.ui.contact.ChatroomContactUI")){
            try {
                indexOf=0;
                selectGroupItem();
            }catch (Exception e){

            }
            return;
       }
       if(WXPageUIManage.isChatRoomUI(className)){
           try {
               isClickGroupItem=false;
               if(totalNum>0){
                   AccessibilityHelper.performBack(servier);
                   totalNum=0;
                   return;
               }
               AccessibilityNodeInfo nodeInfo= AccessibilityHelper.findNodeInfosById(servier.getRootInActiveWindow(),WXIDManage.getWeiXinChatRoomTopBarViewId(weixinVersion));
               if(nodeInfo==null){
                   onStopJob();
                   XToast.error("未知错误!");

               }else {
                   String title=nodeInfo.getChild(1).getText().toString();
                   totalNum=Integer.valueOf(title.substring(title.indexOf("(")+1,title.indexOf(")")));
                   if(totalNum<config.getFilterNum()){
                       AccessibilityHelper.performBack(servier);
                       totalNum=0;
                       return;
                   }
                   AccessibilityHelper.performClick( nodeInfo.getChild(2));
               }
           }catch (Exception e){

           }
           return;
       }

       if(className.equals("com.tencent.mm.plugin.chatroom.ui.ChatroomInfoUI")){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(300);
                        selectContaction();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
           return;
       }
       if(className.equals("com.tencent.mm.plugin.profile.ui.ContactInfoUI")){
           try {
               if(mTimer!=null){
                   mTimer.cancel();
                   mTimer.purge();
                   mTimer=null;
               }
               setTimerTask();
               if(isCheck){
                   AccessibilityHelper.performBack(servier);
                   isCheck=false;
                   return;
               }
               if( addNumber>config.getFilterNum()){

                   AccessibilityNodeInfo addBut=AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"添加到通讯录");
                   if(addBut!=null && AccessibilityHelper.performClick(addBut)){
                       AccessibilityHelper.performClick(addBut);
                       Message message=handler.obtainMessage();
                       message.what=CHECK_FRIEND;
                       message.arg1=-1;
                       handler.sendMessage(message);
                   }else {
                       AccessibilityHelper.performBack(servier);
                       Message message=handler.obtainMessage();
                       message.what=CHECK_FRIEND;
                       message.arg1=1;
                       handler.sendMessage(message);
                   }
               }else {
                   AccessibilityHelper.performBack(servier);
                   Message message=handler.obtainMessage();
                   message.what=CHECK_FRIEND;
                   message.arg1=2;
                   handler.sendMessage(message);
                   AccessibilityHelper.performBack(servier);
               }

           }catch (Exception e){

           }
         return;
       }
       if(className.equals("com.tencent.mm.plugin.profile.ui.SayHiWithSnsPermissionUI")){
           try {
               if(mTimer!=null){
                   mTimer.cancel();
                   mTimer.purge();
                   mTimer=null;
               }

               setTimerTask();
               sendMessage();
           }catch (Exception e){

           }
           return;
       }


    }

    @Override
    public void onStopJob() {
        Log.e("WX_GEOUP","onStopJob");
        Intent intent=new Intent(servier.getApplication(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        servier.getApplication().startActivity(intent);

        WXConfginUtil.closeAddFriendsByGropu();
        try {
            time3.stop();
            if(windowManager!=null && view!=null){
                windowManager.removeView(view);
            }
            view=null;
        }catch (Exception e){

        }
        if(mTimer!=null){
            mTimer.cancel();
            mTimer.purge();
            mTimer=null;
        }
        XToast.success("群加好友已完成",4000).show();
        isStart=false;
        viewAdded=false;
        adds.clear();
        servier.stopAddGroupFriendsJob();


        synchronized (this) {
            // sanity check for null as this is a public method
            if (wakeLock != null) {
                XLog.d("Releasing wakelock");
                try {
                    wakeLock.release();
                } catch (Throwable th) {
                    XLog.e("ignoring this exception, probably wakeLock was already released");

                }
            } else {
                // should never happen during normal workflow
                XLog.e("Wakelock reference is null");
            }
        }



    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void selectGroupItem() {
        try {
            if(isClickGroupItem){
                return;
            }
            List<AccessibilityNodeInfo> nodeInfos=servier.getRootInActiveWindow().findAccessibilityNodeInfosByViewId(WXIDManage.getGroupItemId(weixinVersion));
            AccessibilityNodeInfo groupNodeInfo=null;
            for(int i=0;i<nodeInfos.size();i++){
                AccessibilityNodeInfo n=nodeInfos.get(i);
                checkGroupName=n.getText().toString();
                if(!filterGroups.contains(checkGroupName) && !adds.contains(checkGroupName)){
                    groupNodeInfo=n;
                    break;
                }
            }

            if(groupNodeInfo!=null ){
                isClickGroupItem=true;
                adds.add(checkGroupName);
                Message message=handler.obtainMessage();
                message.what=CHECK_GROUP;
                message.obj=checkGroupName;
                handler.sendMessage(message);
                AccessibilityHelper.performClick(groupNodeInfo);
                isCheck=false;
                indexOf=0;
                addNumber=0;
                return;
            }


            if(AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"个群聊")!=null){
                onStopJob();
                return;
            }else {
                AccessibilityNodeInfo listView=  AccessibilityHelper.findNodeInfosByClassName(servier.getRootInActiveWindow(),WXIDManage.LIST_VIEW);
                if(listView!=null){
                    listView.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    selectGroupItem();
                }
            }
        }catch (Exception e){
            Log.e("WX_GROUP",e.getMessage());
            onStopJob();
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void  selectContaction(){


         List<AccessibilityNodeInfo> nodeInfos=servier.getRootInActiveWindow().findAccessibilityNodeInfosByViewId(WXIDManage.getContactUserAvater(weixinVersion));
        if(nodeInfos==null || nodeInfos.size()==0){//当前群组已全部检测完成
            AccessibilityHelper.performBack(servier);
            return;
        }
        if(indexOf==nodeInfos.size()-1){
            forwardPage();
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            selectContaction();
            return;
        }

        try{
            if(indexOf>nodeInfos.size()){
                indexOf=0;
            }
            AccessibilityNodeInfo nodeInfo=nodeInfos.get(indexOf);
            if(nodeInfo!=null){
                AccessibilityNodeInfo nickNameNodeInfo= nodeInfo.getParent().getChild(0);
                if(nickNameNodeInfo!=null){
                    nickName=nickNameNodeInfo.getText().toString();
                }
                indexOf+=1;
                addNumber+=1;
                Message message=handler.obtainMessage();
                message.what=CHECK_FRIEND;
                message.obj=nickName;
                handler.sendMessage(message);
                if(!addFriends.contains(nickName)){
                    addFriends.add(nickName);
                }
                WeiXinCacheUtil.saveAddFriendsByGroup(servier.getApplication(),addFriends);
                AccessibilityHelper.performClick(nodeInfo);
                isCheck=true;
            }
        }catch (Exception e){
            indexOf+=1;
            addNumber+=1;
            selectContaction();
            return;
        }


    }

    private  AccessibilityNodeInfo getListView(){
        AccessibilityNodeInfo nodeInfo=AccessibilityHelper.findNodeInfosById(servier.getRootInActiveWindow(),"android:id/list");
        return nodeInfo;

    }
    private  void  forwardPage(){
        try {
            AccessibilityNodeInfo nodeInfo=getListView();
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        }catch (Exception e){
            Log.e("WX_GROUP","forwardPage error:"+e.getMessage());
            onStopJob();
        }


    }
    private  void  sendMessage(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try{

                    /**
                     * 获取消息输入框
                     */
                    AccessibilityNodeInfo msgInput = AccessibilityHelper.findNodeInfosById(servier.getRootInActiveWindow(),WXIDManage.getAddGroupMsgInputId(weixinVersion));
                    if (msgInput == null) {
                        //如果没有找到输入框则放弃检测当前好友
                        AccessibilityHelper.performBack(servier);
                        return;
                    }
                    Thread.sleep(300);
                    Bundle arguments = new Bundle();
                    arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, config.getMessage());
                    msgInput.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT,arguments);
                    AccessibilityNodeInfo nodeInfo= AccessibilityHelper.findNodeInfosById(servier.getRootInActiveWindow(),WXIDManage.getWeiXinChatRoomTopBarViewId(weixinVersion));
                    Thread.sleep(300);
                    AccessibilityHelper.performClick(nodeInfo.getChild(2)); //点击发送按钮
                    Message message=handler.obtainMessage();
                    message.what=SEND_MSG;
                    handler.sendMessage(message);
                }catch (Exception e){
                    Log.e("GroupAdd",e.getMessage());
                    AccessibilityHelper.performBack(servier);
                }

            }
        },1000);


    }




    @Override
    public void onNotificationPosted(IStatusBarNotification event) {

    }

    @Override
    public void setWeiXingVersion(int version) {
        this.weixinVersion=version;
    }

    @Override
    public boolean isEnable() {
        return false;
    }


    /**
     * 创建窗口
     */
    private void createWindow(){
        viewAdded=true;
        view = LayoutInflater.from(servier).inflate(R.layout.b_add_friends_group_view, null);
        view.findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStopJob();
            }
        });
        time3=view.findViewById(R.id.time3);
        a1=view.findViewById(R.id.a1);
        tvStatus=view.findViewById(R.id.status);
        msgText=view.findViewById(R.id.msgText);
        tvTotalNum=view.findViewById(R.id.totalNum);
        windowManager= (WindowManager) servier.getSystemService(servier.WINDOW_SERVICE);
        /*
         * LayoutParams.TYPE_SYSTEM_ERROR：保证该悬浮窗所有View的最上层
         * LayoutParams.FLAG_NOT_FOCUSABLE:该浮动窗不会获得焦点，但可以获得拖动
         * PixelFormat.TRANSPARENT：悬浮窗透明
         */
        layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT);
        layoutParams.flags = layoutParams.flags | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        layoutParams.flags = layoutParams.flags | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; // 排版不受限制
        //悬浮窗开始在右下角显示
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        startWarp=view.findViewById(R.id.startWarp);
        mainWarp=view.findViewById(R.id.mainWarp);
        timepicker=view.findViewById(R.id.timepicker);
        windowManager.addView(view,layoutParams);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(view.getVisibility()==View.GONE){
                    WXConfginUtil.closeAddFriendsByGropu();
                    XToast.error("旺旺通悬浮窗权限");
                    windowManager.removeView(view);
                    Intent intent=new Intent(servier.getApplication(), MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    servier.getApplication().startActivity(intent);
                    servier.stopAddGroupFriendsJob();
                    return;
                }
                new com.wgj.android.utils.Timer(timepicker, new com.wgj.android.utils.Timer.OnCountTimerListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                    @Override
                    public void onFinish() {
                        startWarp.setVisibility(View.GONE);
                        mainWarp.setVisibility(View.VISIBLE);
                        a1.startAnimation(createRotateAnimation(360,-360,5000));
                        time3.setBase(SystemClock.elapsedRealtime());//计时器清零
                        int hour = (int) ((SystemClock.elapsedRealtime() - time3.getBase()) / 1000 / 60);
                        time3.setFormat("0"+String.valueOf(hour)+":%s");
                        time3.start();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"通讯录"));
                                while (!isStart){
                                    try {
                                        Thread.sleep(300);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    AccessibilityNodeInfo n=AccessibilityHelper.findNodeInfosByText(servier.getRootInActiveWindow(),"群聊");
                                    if(n==null){
                                        getListView().performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
                                    }else {
                                        isStart=true;
                                        AccessibilityHelper.performClick(n);
                                    }
                                }
                            }
                        },200);


                    }
                }).start();
            }
        },300);


    }

    /**
     * 创建旋转动画
     */
    private RotateAnimation createRotateAnimation(int fromDegress, int toDegrees, int duration) {
        RotateAnimation animation = new RotateAnimation(fromDegress, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //动画执行时间
        animation.setDuration(duration);
        animation.setInterpolator(new LinearInterpolator());
        //动画重复次数-1表示不停重复
        animation.setRepeatCount(-1);
        return  animation;
    }
    /**
     * uI更新
     */
    Handler handler = new Handler()
    {
        public void handleMessage(android.os.Message msg) {
            try {
                switch (msg.what){
                    case  SEND_MSG:
                        msgText.setText("正在向:"+nickName+"发送好友申请");
                        tvTotalNum.setText(String.valueOf(Integer.valueOf(tvTotalNum.getText().toString())+1));
                        break;
                    case CHECK_GROUP:
                        msgText.setText("正在检测群:"+msg.obj);
                        break;
                    case CHECK_FRIEND:
                        if(msg.arg1==-1){
                            tvStatus.setText("陌生人");
                        }else if(msg.arg1==1){
                            tvStatus.setText("好友");
                        }else {
                            msgText.setText("正在检测:【"+msg.obj+"】  好友关系");
                            tvStatus.setText(">>>>");
                        }
                        break;
                }
            }catch (Exception e){

            }


        };
    };


    private void setTimerTask() {
        if (mTimer==null){
            mTimer=new Timer();
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    isToSendMsg=false;
                    AccessibilityHelper.performBack(servier);
                }catch (Exception e){

                }

            }
        }, 10000);
    }
}
